library(tidyverse)
library(grid)
library(gridExtra)

load("cleandata.Rda")

election2017facet = election2017 %>%
  filter(east == 0 | east == 1) %>%
  gather(measure, value, c(afd, logdens, forn, migrant, unemp,
                            loggdppc, avgage, avged, minorleft))

election2017facet$measure = election2017facet$measure %>%
  str_replace("afd", "AfD vote share") %>%
  str_replace("logdens", "Log pop density") %>%
  str_replace("forn", "Foreign-born pop") %>%
  str_replace("migrant", "Migrant-origin pop") %>%
  str_replace("unemp", "Unemployment") %>%
  str_replace("loggdppc", "Log GDP per capita") %>%
  str_replace("avgage", "Average age") %>%
  str_replace("avged", "Average education") %>%
  str_replace("minorleft", "Minor left vote") %>%
  factor(levels = c("AfD vote share",
                    "Log pop density",
                    "Foreign-born pop",
                    "Migrant-origin pop",
                    "Unemployment",
                    "Log GDP per capita",
                    "Average age",
                    "Average education",
                    "Minor left vote"))

theme_boxplots = theme(axis.title.y = element_blank(),
                       axis.title.x = element_blank(),
                       strip.placement = "outside",
                       strip.background = element_blank(),
                       strip.switch.pad.wrap = margin(0, 0, 0, 0))

facets = election2017facet %>%
  filter(measure != "AfD vote share") %>%
  ggplot(aes(x = east, y = value, fill = factor(east))) +
  geom_boxplot(notch = T, outlier.alpha = 1/3) +
  scale_fill_grey(start = 0.8, end = 1) +
  scale_x_continuous(breaks = c(0, 1), labels = c("West", "East")) +
  facet_wrap(measure ~ ., scales = "free_y",
             strip.position = "top", ncol = 4) +
  guides(fill = F) +
  theme_bw() +
  theme(plot.margin = margin(0, 0, 0, 0, "pt")) +
  theme_boxplots

afdbox = election2017facet %>%
  filter(measure == "AfD vote share") %>%
  ggplot(aes(x = east, y = value, fill = factor(east))) +
  geom_boxplot(notch = T, outlier.alpha = 1/3) +
  scale_fill_grey(start = 0.8, end = 1) +
  scale_x_continuous(breaks = c(0, 1), labels = c("West", "East")) +
  facet_wrap(measure ~ ., scales = "free_y",
             strip.position = "top", ncol = 1) +
  guides(fill = F) +
  theme_bw() +
  theme(plot.margin = margin(t = 0, r = 5.5, b = 0, l = 0, "pt")) +
  theme_boxplots

boxplots = arrangeGrob(afdbox, facets, widths = list(1, 4))

ggsave("boxplots.tiff", plot = boxplots, scale = 1.15, width = 6.5,
       height = 3.5, units = "in", dpi = 2400)
